<?php
include "DBConnection.php";
include "model/Track.php";

$connection = new DBConnection();
$connection -> connect();
$userID = $_REQUEST['userID'];
$date = $_REQUEST['date'];
$carID = $_REQUEST['carID'];

$userCheck = false;
$carCheck = false;

$checkUserQuery = "SELECT user.name FROM user WHERE user.id = ?";
$checkCarQuery = "SELECT car.name FROM car WHERE car.id = ?";

$statement = $connection -> query($checkUserQuery, array($userID));
if (count($statement -> fetchAll()) > 0) {
	$userCheck = true;
}

$statement2 = $connection -> query($checkCarQuery, array($carID));
if (count($statement2 -> fetchAll()) > 0) {
	$carCheck = true;
}

if ($userCheck && $carCheck && $date != NULL) {
	$car_user_id = get_user_car_ID($connection, $userID, $carID);
	$createTrackQuery = "INSERT INTO track (date, user_car_id) VALUES (?, ?)";
	$arguments = array($date, $car_user_id);
	$statement = $connection -> query($createTrackQuery, $arguments);

	if ($statement) {

		$query = "SELECT id, date FROM track ORDER BY id DESC LIMIT 1";
		$statement = $connection -> query($query, array());

		$result = $statement -> fetchObject();
		$track = new Track();
		$track -> id = $result -> id;
		$track -> date = $result -> date;

		echo json_encode($track);
	} else {
		echo "DATABASE ERROR";
	}
} else {
	echo "{
	\"track\" : {
		\"status\" : 404,
		\"error\" : \"Car or User not found or date is null or something\"
	}
}";

}

function get_user_car_ID(DBConnection $connection, $userID, $carID) {
	$query = "INSERT INTO user_car(user_id, car_id) VALUES (?, ?)";
	$arguments = array($userID, $carID);
	$statement = $connection -> query($query, $arguments);

	$query = "SELECT id FROM user_car ORDER BY id DESC LIMIT 1";
	$statement = $connection -> query($query, array());

	$result = $statement -> fetchObject();
	return $result -> id;
}
?>